<template>
  <div>
    <div style="font-size: 30px;text-align: center; ">
      <div v-if="todayCheckin">
        <div>还知道签到呀 😒</div>
      </div>
      <div v-else>
        <div>今天您签到了 ❓</div>
      </div>
    </div>

    <div style="width: 100%;display: flex;margin-top: 20px">
      <el-card class="canlendar" :style="getCalerndarStyle" :class="[theme ? theme : '']">
        <div class="canlendar_title">
          <div v-if="!$slots.header" class="flex flex-center">
            <div @click="prevYear" class="canlendar_button" style="margin-right: 5px">上一年</div>
            <div @click="prevMonth" class="canlendar_button">上一月</div>
            <div class="year">
              <span>{{ this.year }}</span>
              年 -
              <span>{{ this.month >= 10 ? this.month : '0' + this.month }}</span>
              月
            </div>
            <div @click="nexMonth" class="canlendar_button" style="margin-right: 5px">下一月</div>
            <div @click="nextYear" class="canlendar_button">下一年</div>
          </div>
          <slot name="header"></slot>
        </div>
        <div class="canlendar_content flex flex-wrap">
          <div class="header-item flex flex-column flex-center" v-for="item in weekArr">
            <div>{{ item }}</div>
          </div>
          <div
              v-for="item in dayArr"
              :class="[
					    item.isCurrentMonth ? '' : 'item-disabled',
					    item.isSelected && !item.isToday ? 'canlendar_selected' : '',
					    item.isToday ? 'canlendar_today' : '',
					    'item canlendar_item flex flex-column flex-center',]"
              @click="dateClick(item)">
            <div>{{ item.day }}</div>
          </div>
        </div>
      </el-card>

      <div style="margin-left:30px;width: 40%">
        <el-card class="box-card" style="margin-right: 50px;width: 70%">
          {{ this.year }}年总签到次数: {{ signData.yearSign }}<br><br>
          {{ this.month }}月份签到次数: {{ this.signData.monthSign }}<br><br>
          当月连续签到次数: {{ signData.signCount }}<br>
        </el-card>
        <el-card class="box-card" style="margin-right: 30px;margin-top: 30px;height: 300px">
          <div style="width: 100%;height: 300px" id="main"></div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import moment from 'moment';

import * as echarts from 'echarts';

export default {
  name: 'Calendar',
  data() {
    let year = moment().year();
    let month = moment().month() + 1;
    let day = moment().date();
    return {
      todayCheckin: false,
      today: moment().format('YYYY-MM-DD'),
      year: year,
      month: month,
      day: day,
      dayArr: [],
      weekArr: ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'],
      //签到次数数据
      signData: {
        yearSign: 0,
        monthSign: 0,
        signCount: 0,
        DaySignCount: 0,
      },
    };
  },
  props: {
    width: {
      type: [Number, String],
      default: '800px',
    },
    height: {
      type: [Number, String],
      default: '',
    },
    currentTime: {
      type: String,
      default: '',
    },
    theme: {
      type: String,
      default: '',
    },
    autoMonthSwitch: {
      type: Boolean,
      default: true,
    },
  },
  computed: {
    getCalerndarStyle() {
      return {
        width: this.width,
        height: this.height,
      };
    },
  },
  //监听年份、月份变化，发送请求
  watch: {
    month: {
      immediate: true,
      handler() {
        this.signDataCount()
      }
    },
    year: {
      handler() {
        this.quarterDataFunction()
        this.signDataCount()
      }
    },

  },
  created() {
    if (this.currentTime && moment(this.currentTime).isValid()) {
      this.day = moment(this.currentTime).date();
      this.month = moment(this.currentTime).month() + 1;
      this.year = moment(this.currentTime).year();
      this.today = this.currentTime;
    }
    this.build();
  },
  mounted() {
    this.quarterDataFunction()
  },
  beforeMount() {
    this.todayIsCheckin()
  },
  methods: {
    todayIsCheckin() {
      let date = new Date(),
          year = date.getFullYear(), //获取完整的年份(4位)
          month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
          strDate = date.getDate() // 获取当前日(1-31)
      this.request.get("/checkin/isCheckin/" + year + "-" + month + "-" + strDate).then(
          res => {
            if (res.code == 200 && res.data == 1) {
              this.todayCheckin = true
            }
          }
      )
    },
    //统计已选月的签到数
    signDataCount() {
      this.request.get("/checkin/signCount/" + this.year + "-" + this.month).then(
          res => {
            if (res.code == 200) {
              this.signData.yearSign = res.data.yearSign
              this.signData.monthSign = res.data.monthSign
              if (res.data.signCount != null) {
                this.signData.DaySignCount = res.data.signCount
              }
              this.signData.signCount = res.data.signCount == null ? this.signData.DaySignCount : res.data.signCount
            }
          }
      )
    },
    //
    quarterDataFunction() {
      var chartDom = document.getElementById('main');
      var myChart = echarts.init(chartDom);
      var option = {
        title: {
          text: this.year + '季度签到表',
          textStyle: {
            size: 10
          },
          left: 'center'
        },
        xAxis: {
          type: 'category',
          data: ['第一季度', '第二季度', '第三季度', '第四季度']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: [80, 54, 120, 70],
            type: 'line'
          },
          {
            data: [80, 54, 120, 70],
            type: 'bar'
          }
        ]
      };
      //图表信息统计
      this.request.get("/checkin/quarterData/" + this.year).then(res => {
        if (res.code == 200) {
          console.log(res.data)
          option.series[0].data = res.data
          option.series[1].data = res.data
          myChart.setOption(option);
        }
      })
    },
    prevMonth() {
      this.build(this.year, this.month - 1, this.day);
    },
    nexMonth() {
      this.build(this.year, this.month + 1, this.day);
    },
    prevYear() {
      this.build(this.year - 1, this.month, this.day);
    },
    nextYear() {
      this.build(this.year + 1, this.month, this.day);
    },
    backToToday() {
      let year = this.today.split('-')[0];
      let month = this.today.split('-')[1];
      let day = this.today.split('-')[2];
      this.build(year, month, day);
    },
    change() {
      let fullDate = moment(
          this.year + '-' + this.month + '-' + this.day,
          'YYYY-MM-DD'
      ).format();
      this.$emit('change', fullDate);
    },
    dateClick(item) {
      if (this.autoMonthSwitch) {
        //点击上月日期
        if (!item.isCurrentMonth && item.month < this.month) {
          this.prevMonth();
          return;
        }
        //点击下月日期
        if (!item.isCurrentMonth && item.month > this.month) {
          this.nexMonth();
          return;
        }
      }
      this.dayArr = this.dayArr.map(day => {
        day.isSelected = false;
        if (day.day === item.day && day.month === item.month) {
          day.isSelected = true;
        }
        return day;
      });
      this.$emit('dateClick', item);
      this.$emit(
          'update:currentTime',
          moment(this.year + '-' + this.month + '-' + item.day, 'YYYY-MM-DD').format(
              'YYYY-MM-DD'
          )
      );
      //签到
      this.request.get("/checkin/signIn/" + this.year + "-" + this.month + "-" + item.day).then(
          res => {
            if (res.code == 200) {
              this.$message.success(res.data)
              this.signDataCount()
              this.quarterDataFunction()
              //签到当前的日期
              let date = new Date(),
                  year = date.getFullYear(), //获取完整的年份(4位)
                  month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
                  strDate = date.getDate() // 获取当前日(1-31)
              if (this.year == year && this.month == month && item.day == strDate) {
                this.todayIsCheckin()
              }
            }
            if (res.code == 600) {
              this.$message.error(res.msg)
            }
          }
      )
    },
    build: function (year, month, day) {
      year = year || this.year;
      month === 0 ? (month = -1) : (month = month || this.month);
      day = day || this.day;

      if (month <= 0) {
        year = year - 1;
        month = 12;
      }

      if (month > 12) {
        year = year + 1;
        month = 1;
      }

      this.year = year;
      this.month = month;
      this.day = day;

      //获取当前年月可用天数
      let days = moment(year + '-' + month, 'YYYY-MM').daysInMonth();
      //计算当前月份第一天是周几
      let firstDay = moment(year + '-' + month + '-01', 'YYYY-MM-DD').day();
      this.dayArr = [];
      //构建日历数组
      //构建上个月的日期
      for (let i = 1; i < firstDay; i++) {
        //获取上个月的天数
        let lastMonthDays = moment(year + '-' + month, 'YYYY-MM')
            .subtract(1, 'months')
            .daysInMonth();
        //计算上个月的日期
        let lastMonthDay = lastMonthDays - firstDay + i + 1;
        //前面补空
        this.dayArr.push({
          day: lastMonthDay,
          month: month - 1,
          isCurrentMonth: false,
        });
      }
      //构建当前月份的日期
      for (let i = 1; i <= days; i++) {
        let fullDate = moment(year + '-' + month + '-' + i, 'YYYY-MM-DD').format(
            'YYYY-MM-DD'
        );
        let isToday = false;
        if (fullDate === this.today) {
          isToday = true;
        }
        if (i === day && isToday) {
          this.dayArr.push({
            month: month,
            day: i,
            isCurrentMonth: true,
            isSelected: true,
            isToday: true,
          });
        } else {
          this.dayArr.push({
            month: month,
            day: i,
            isCurrentMonth: true,
          });
        }
      }
      //构建下个月的日期
      let nextMonthDay = 1;
      while (this.dayArr.length < 35) {
        this.dayArr.push({
          day: nextMonthDay,
          month: month + 1,
          isCurrentMonth: false,
        });
        nextMonthDay++;
      }

      if (this.dayArr.length > 35) {
        //构建下个月的日期
        let nextMonthDay = 1;
        while (this.dayArr.length < 42) {
          this.dayArr.push({
            day: nextMonthDay,
            month: month + 1,
            isCurrentMonth: false,
          });
          nextMonthDay++;
        }
      }
      this.change();
    }
  }
}
</script>

<style>
.flex {
  display: flex;
}

.absolute {
  position: absolute;
}

.relative {
  position: relative;
}

.justify-content-center {
  justify-content: center;
}

.flex-inline {
  display: inline-flex;
}

.flex-center {
  align-items: center;
  justify-content: center;
}

.flex-between {
  justify-content: space-between;
}

.flex-end {
  justify-content: flex-end;
}

.flex-start {
  justify-content: flex-start;
}

.flex-wrap {
  flex-wrap: wrap;
}

.flex-nowrap {
  flex-wrap: nowrap;
}

.flex-auto {
  flex: 1 1 auto;
}

.flex-align-center {
  align-items: center;
}

.flex-column {
  flex-direction: column;
}

.flex-evenly {
  justify-content: space-evenly;
}

.w-full {
  width: 100%;
}

.canlendar {
  --color-primary-text: #4178be;
  --color-primary-light: #5cb4ff;
  --color-canlender-bg: #eff5ff;
  --color-light-white: #f0f0f0;
  border: 1px solid var(--color-light-white);
}

.canlendar.dark {
  --color-primary-text: #8fa9d0;
  --color-primary-light: #a6559d;
  --color-canlender-bg: #2c2c2c;
  --color-light-white: #2f2f2f;
  border: 1px solid var(--color-light-white);
}

.canlendar .canlendar_button {
  padding: 5px;
  border: 1px solid var(--color-light-white);
  cursor: pointer;
  user-select: none;
}

.canlendar .canlendar_button:hover {
  background: var(--color-canlender-bg);
}

.canlendar.dark .canlendar_button:hover {
  color: white;
}

.canlendar .canlendar_title {
  padding: 20px;
  width: 100%;
  position: relative;
}

.canlendar .canlendar_title .year {
  margin: 0 30px;
  font-size: 20px;
  font-family: Arial;
}

.canlendar .canlendar_title img {
  cursor: pointer;
}

.canlendar .canlendar_content {
  position: relative;
  width: 100%;
}

.canlendar_content .item {
  box-sizing: border-box;
  border: 1px solid var(--color-light-white);
  width: 14.28%;
  height: 60px;
  cursor: pointer;
  transition: all 0.3s;
}

.canlendar_content .item-disabled {
  background: var(--color-light-white);
}

.canlendar.dark .canlendar_content .item-disabled {
  color: white;
}

.canlendar_content .header-item {
  box-sizing: border-box;
  border: 1px solid var(--color-light-white);
  width: 14.28%;
  height: 50px;
}

.canlendar_content .item:hover,
.canlendar_selected {
  border: 1px solid var(--color-canlender-bg);
  background: var(--color-canlender-bg);
}

.canlendar.dark .canlendar_content .item:hover,
.canlendar.dark .canlendar_selected {
  color: white;
}

.canlendar .canlendar_today {
  background: var(--color-primary-light);
  color: white;
  border-radius: 12%;
  text-align: center;
}

.canlendar .canlendar_today:hover {
  background: var(--color-primary-light);
}

.canlendar_content .item .rounded {
  margin-top: 10px;
  width: 26px;
  height: 26px;
  line-height: 26px;
  background: var(--color-primary-text);
  border-radius: 50%;
  text-align: center;
  color: white;
}
</style>
